package cn.congine.wizarpos.mall.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.congine.wizarpos.mall.model.MrtTicketDef;
import cn.congine.wizarpos.mall.model.open.AccessTokenInput;
import cn.congine.wizarpos.mall.model.open.CommonResultOutput;
import cn.congine.wizarpos.mall.model.open.MerchantDef;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryInput;
import cn.congine.wizarpos.mall.model.open.MerchantDefQueryOutput;
import cn.congine.wizarpos.mall.model.open.TicketDefInfoInput;
import cn.congine.wizarpos.mall.model.open.TicketDefInfoOutput;
import cn.congine.wizarpos.mall.model.open.TicketToPackageInput;
import cn.congine.wizarpos.mall.model.open.TicketToPackageOutput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberTicketAddInput;
import cn.congine.wizarpos.mall.model.open.WeChartMemberTicketAddOutput;
import cn.congine.wizarpos.mall.service.impl.WizarposOpenRestClient;
import cn.congine.wizarpos.mall.utils.SysConstants;
import cn.congine.wizarpos.mall.utils.WxSignUtil;

@Controller
@RequestMapping(value = "/hongbao")
public class HongbaoAction {
	private final Log log = LogFactory.getLog(getClass());

	@Resource(name = "messageSource")
	private MessageSource messageSource;
	
	@Autowired
	private WizarposOpenRestClient wizarposOpenRestClient;
	/**
	 * 进入无红包页面
	 * 
	 * @param mid
	 * @param ticketId
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/no_hongbao")
	public ModelAndView noHongbao(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "openId", required = true) String openId) {

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("mid", mid);
		data.put("openId", openId);

		return new ModelAndView("hongbao/no_hongbao", data);
	}

	/**
	 * 非会员，领取红包要先注册
	 * 
	 * @param mid
	 * @param ticketId
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/register")
	public ModelAndView register(
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "openId", required = true) String openId) {
		Map<String, Object> data = new HashMap<String, Object>();
		// 商户数据
		MerchantDefQueryInput input = new MerchantDefQueryInput();
		input.setMid(mid);
		MerchantDefQueryOutput output = (MerchantDefQueryOutput) wizarposOpenRestClient.post(input, "/merchantdef/info", MerchantDefQueryOutput.class);		
		if (output != null && SysConstants.OPEN_SUCCESS.equals(output.getCode())) {
			MerchantDef merchantDef = output.getResult();
			if (merchantDef != null) {
				data.put("logoImage", merchantDef.getLogoImage());
				data.put("merchantName", merchantDef.getLogoImage());
			}
		}
				
		data.put("mid", mid);
		data.put("openId", openId);

		return new ModelAndView("hongbao/register", data);
	}

	/**
	 * 红包详情，要使用微信分享，所以要签名js
	 * 
	 * @param ticketId
	 *            : MrtTicketDef.id
	 * @param openId
	 * @param mid
	 * @param httpRequest
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/detail")
	public ModelAndView detail(
			@RequestParam(value = "ticketId", required = true) String ticketId,
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("mid", mid);
		data.put("openId", openId);

		TicketDefInfoInput input = new TicketDefInfoInput();
		input.setTicketDefIds(Arrays.asList(ticketId));
		TicketDefInfoOutput output = (TicketDefInfoOutput) wizarposOpenRestClient.post(input, "/wechart/ticketdef/info", TicketDefInfoOutput.class);		
		MrtTicketDef ticketDef = null;
		if (output == null || SysConstants.OPEN_ERROR.equals(output.getCode())) {
			return new ModelAndView("hongbao/no_hongbao", data);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(output.getCode())) {
			return new ModelAndView("hongbao/no_hongbao", data);
		} else {
			ticketDef  = output.getResult().get(0);
		}
		
		if (ticketDef == null
				|| ticketDef.getHbUseNum() == null
				|| (ticketDef.getHbBonusNum() != null && ticketDef
						.getHbUseNum() >= ticketDef.getHbBonusNum())) {
			return new ModelAndView("hongbao/no_hongbao", data);
		}
		data.put("ticketDef", ticketDef);

		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/hongbao/detail");
		tmpUrl.append("?mid=").append(mid);
		tmpUrl.append("&openId=").append(openId);
		tmpUrl.append("&ticketId=").append(ticketId);
		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}
		
		String dns = url.substring(url.indexOf("//") + 2,
				url.indexOf("/wizarpos-mall-sole"));
		data.put("dns", dns);

		return new ModelAndView("hongbao/detail", data);
	}

	/**
	 * 领取红包
	 * 
	 * @param mid
	 * @param ticketId
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/receive")
	public @ResponseBody String receive(
			@RequestParam(value = "ticketId", required = true) String ticketId,
			@RequestParam(value = "mid", required = true) String mid,
			@RequestParam(value = "openId", required = true) String openId) {
		//请求开放平台	
		WeChartMemberTicketAddInput input = new WeChartMemberTicketAddInput();
		input.setMid(mid);
		input.setOpenId(openId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ticketId", ticketId);
		map.put("ticketNum", 1);
		List<Map<String, Object>> ticketIds = new ArrayList<Map<String, Object>>();
		ticketIds.add(map);		
		input.setTicketIds(ticketIds);
		input.setWxAdded('0');
		input.setHbShared("0");
		input.setRemark("红包券");		
		input.setHongbao("1");//领取红包操作标志
		WeChartMemberTicketAddOutput output = (WeChartMemberTicketAddOutput) wizarposOpenRestClient.post(input, "/wechart/ticket/add", WeChartMemberTicketAddOutput.class);		
		if (output == null || "-1".equals(output.getCode())) {
			return "3";//处理失败，系统错误
		}  else if ("60062".equals(output.getCode())) {//红包已领取
			return "2";
		} else if ("60063".equals(output.getCode())) {//红包已发完
			return "1";
		} else if ("0".equals(output.getCode())) {//操作成功
			return "0";			
		} else {//其他错误，包括非法商户号，非法微信号，非法入参
			return "3";
		}
	}
	
	
	/**
	 * 用户分享红包后，更新分享标记为已经分享
	 * 
	 * @param ticketId
	 * @param mid
	 * @param httpRequest
	 * @throws Exception
	 */
	@RequestMapping(value = "/after_share")
	public @ResponseBody String afterShare(
			@RequestParam(value = "ticketId", required = true) String ticketId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) {

		TicketToPackageInput input = new TicketToPackageInput();
		input.setMid(mid);
		input.setId(ticketId);		
		TicketToPackageOutput output = (TicketToPackageOutput) wizarposOpenRestClient.post(input, "/wechart/ticket/topackage", TicketToPackageOutput.class);
		if (output != null && "0".equals(output.getCode())) {
			return "0";
		} else {
			return "1";
		}
	}

	/**
	 * 微信卡包卡券，所以要签名js
	 * 
	 * @param ticketId
	 *            : MrtTicketDef.id
	 * @param openId
	 * @param mid
	 * @param httpRequest
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/kqList")
	public ModelAndView kaquanList(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("mid", mid);
		data.put("openId", openId);

		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/hongbao/kqList");
		tmpUrl.append("?mid=").append(mid);
		tmpUrl.append("&openId=").append(openId);

		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}	
		return new ModelAndView("kaquan/quan", data);
	}
	
	/**
	 * 微信卡包卡券，所以要签名js
	 * 
	 * @param ticketId
	 *            : MrtTicketDef.id
	 * @param openId
	 * @param mid
	 * @param httpRequest
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/kqdetail")
	public ModelAndView kaquanDetail(
			@RequestParam(value = "openId", required = true) String openId,
			@RequestParam(value = "mid", required = true) String mid,
			HttpServletRequest httpRequest) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("mid", mid);
		data.put("openId", openId);

		// 请求微信 js api的完整页面地址
		String baseUrl = "http://"
				+ messageSource.getMessage(SysConstants.SERVICE_DNS, null,
						Locale.ENGLISH);
		baseUrl += httpRequest.getSession().getServletContext()
				.getContextPath();
		StringBuffer tmpUrl = new StringBuffer();
		tmpUrl.append(baseUrl);
		tmpUrl.append("/hongbao/kqdetail");
		tmpUrl.append("?mid=").append(mid);
		tmpUrl.append("&openId=").append(openId);

		String url = tmpUrl.toString();
		// 请求微信api的ticket
		AccessTokenInput jsInput = new AccessTokenInput();
		jsInput.setMid(mid);
		CommonResultOutput jsOutput = (CommonResultOutput) wizarposOpenRestClient.post(jsInput, "/weixin/ticket/js", CommonResultOutput.class);		
		if (jsOutput == null || SysConstants.OPEN_ERROR.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.OPEN_ERROR);
		} else if (SysConstants.NO_MERCHANT_CODE.equals(jsOutput.getCode())) {
			return new ModelAndView("error").addObject("err_message",
					SysConstants.NO_MERCHANT);
		} else {
			Map<String, String> result = (Map<String, String>) jsOutput.getResult();
			String jsTicket = result.get("ticket");
			String appid = result.get("appid");
			data.put("appId", appid);
			Map<String, String> ret = WxSignUtil.commonSign(jsTicket, url,
					WxSignUtil.createTimestamp());
			data.putAll(ret);
		}								
		return new ModelAndView("kaquan/quan", data);
	}
}
